<template>
  <div class="ele-body">
    <el-card shadow="never">
      <!-- 搜索表单 -->
      <el-form
        :model="where"
        label-width="100px"
        class="ele-form-search"
        @keyup.enter.native="reload"
        @submit.native.prevent>
        <el-row :gutter="15">
          <el-col :lg="6" :md="12">
            <el-form-item label="订单编号:">
              <el-input
                clearable
                v-model="where.order_no"
                placeholder="请输入邻工订单号或船到订单号">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="12">
            <el-form-item label="订单状态:">
              <el-select
                clearable
                v-model="where.order_status"
                placeholder="请选择状态"
                class="ele-fluid">
                <el-option label="待接单" :value="1"></el-option>
                <el-option label="已接单" :value="2"></el-option>
                <el-option label="取货中" :value="3"></el-option>
                <el-option label="配送中" :value="4"></el-option>
                <el-option label="已完成" :value="5"></el-option>
                <el-option label="已取消" :value="6"></el-option>
                <el-option label="异常" :value="7"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :lg="6" :md="12">
            <el-form-item label="创建时间:">
              <el-date-picker
                v-model="dateRange"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                format="yyyy-MM-dd HH:mm"
                value-format="yyyy-MM-dd HH:mm:ss"
                class="ele-fluid">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <div class="ele-form-actions">
              <el-button
                type="primary"
                icon="el-icon-search"
                class="ele-btn-icon"
                @click="reload">查询
              </el-button>
              <el-button @click="reset">重置</el-button>
              <el-button
                type="success"
                icon="el-icon-refresh"
                @click="refreshRealtime"
                :loading="refreshLoading">刷新实时状态
              </el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>

      <!-- 统计面板 -->
      <div class="order-stats" v-if="stats">
        <el-row :gutter="20">
          <el-col :span="4">
            <div class="stat-card total">
              <div class="stat-icon">
                <i class="el-icon-document"></i>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ stats.total_orders }}</div>
                <div class="stat-label">总订单</div>
              </div>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="stat-card pending">
              <div class="stat-icon">
                <i class="el-icon-time"></i>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ stats.pending_orders }}</div>
                <div class="stat-label">待接单</div>
              </div>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="stat-card processing">
              <div class="stat-icon">
                <i class="el-icon-truck"></i>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ stats.processing_orders }}</div>
                <div class="stat-label">配送中</div>
              </div>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="stat-card completed">
              <div class="stat-icon">
                <i class="el-icon-circle-check"></i>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ stats.completed_orders }}</div>
                <div class="stat-label">已完成</div>
              </div>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="stat-card cancelled">
              <div class="stat-icon">
                <i class="el-icon-circle-close"></i>
              </div>
              <div class="stat-content">
                <div class="stat-value">{{ stats.cancelled_orders }}</div>
                <div class="stat-label">已取消</div>
              </div>
            </div>
          </el-col>
          <el-col :span="4">
            <div class="stat-card amount">
              <div class="stat-icon">
                <i class="el-icon-money"></i>
              </div>
              <div class="stat-content">
                <div class="stat-value">¥{{ formatAmount(stats.total_amount) }}</div>
                <div class="stat-label">总金额</div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>

      <!-- 数据表格 -->
      <ele-pro-table
        ref="table"
        :where="tableWhere"
        :datasource="url"
        :columns="columns"
        :selection.sync="selection"
        height="calc(100vh - 520px)"
        cache-key="chuandaoOrderTable">

        <!-- 表头工具栏 -->
        <template slot="toolbar">
          <el-button
            size="small"
            type="success"
            icon="el-icon-download"
            class="ele-btn-icon"
            @click="exportData">导出订单
          </el-button>

          <el-button
            size="small"
            type="primary"
            icon="el-icon-refresh"
            @click="batchRefreshStatus"
            style="margin-left: 10px;">
            刷新状态
          </el-button>
        </template>

        <!-- 订单信息列 -->
        <template slot="order_info" slot-scope="{row}">
          <div class="order-info">
            <div class="order-main">
              <div class="order-no">{{ row.neighbor_order_no || row.order_no }}</div>
              <div class="order-time">{{ formatDate(row.created_at) }}</div>
            </div>
            <div class="order-id">
              <span v-if="row.neighbor_order_no">船到订单: {{ row.order_no }}</span>
              <span v-else>ID: {{ row.id }}</span>
            </div>
          </div>
        </template>


        <!-- 配送信息列 -->
        <template slot="delivery_info" slot-scope="{row}">
          <div class="delivery-info">
            <div class="delivery-item">
              <span class="label">取货:</span>
              <span class="address">{{ row.pickup_address }}</span>
            </div>
            <div class="delivery-item">
              <span class="label">送达:</span>
              <span class="address">{{ row.delivery_address }}</span>
            </div>
          </div>
        </template>

        <!-- 订单状态列 -->
        <template slot="order_status" slot-scope="{row}">
          <div class="status-info">
            <el-tag :type="getOrderStatusColor(row.order_status)" size="small">
              {{ getOrderStatusText(row.order_status) }}
            </el-tag>
            <div class="status-time" v-if="row.status_updated_at">
              {{ formatDate(row.status_updated_at) }}
            </div>
          </div>
        </template>

        <!-- 骑手信息列 -->
        <template slot="rider_info" slot-scope="{row}">
          <div class="rider-info" v-if="row.rider_name">
            <div class="rider-main">
              <span class="rider-name">{{ row.rider_name }}</span>
              <el-button
                type="text"
                size="mini"
                @click="showRiderLocation(row)"
                v-if="row.order_status >= 2 && row.order_status <= 4">
                <i class="el-icon-location-information"></i>
              </el-button>
            </div>
            <div class="rider-mobile">{{ row.rider_mobile }}</div>
          </div>
          <div v-else class="no-rider">
            <span>暂未分配</span>
          </div>
        </template>

        <!-- 订单金额列 -->
        <template slot="order_amount" slot-scope="{row}">
          <div class="amount-info">
            <div class="total-amount">¥{{ formatAmount(row.total_amount) }}</div>
            <div class="fee-detail" v-if="row.delivery_fee">
              配送费: ¥{{ formatAmount(row.delivery_fee) }}
            </div>
          </div>
        </template>

        <!-- 操作列 -->
        <template slot="action" slot-scope="{row}">
          <el-button
            type="text"
            size="small"
            icon="el-icon-view"
            @click="showOrderDetail(row)">详情
          </el-button>
          <el-button
            v-if="row.order_status >= 2 && row.order_status <= 4"
            type="text"
            size="small"
            icon="el-icon-refresh"
            @click="refreshOrderStatus(row)">状态
          </el-button>
          <el-button
            v-if="canCancelOrder(row)"
            type="text"
            size="small"
            icon="el-icon-close"
            style="color: #F56C6C;"
            @click="cancelOrder(row)">取消
          </el-button>
          <el-dropdown
            @command="handleOrderAction"
            style="margin-left: 5px;"
            :data="row">
            <el-button type="text" size="small">
              更多<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item :command="{action: 'track', row}">订单追踪</el-dropdown-item>
              <el-dropdown-item :command="{action: 'refund', row}" v-if="canRefundOrder(row)">申请退款</el-dropdown-item>
              <el-dropdown-item :command="{action: 'complaint', row}">投诉建议</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </ele-pro-table>
    </el-card>

    <!-- 订单详情弹窗 -->
    <el-dialog
      title="订单详情"
      :visible.sync="detailVisible"
      width="900px"
      :close-on-click-modal="false">
      <div v-if="currentOrder">
        <!-- 基础信息 -->
        <el-descriptions title="基础信息" :column="3" border>
          <el-descriptions-item label="订单编号">{{ currentOrder.neighbor_order_no || currentOrder.order_no }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getOrderStatusColor(currentOrder.status)" size="small">
              {{ currentOrder.status_text || getOrderStatusText(currentOrder.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDate(currentOrder.local_info && currentOrder.local_info.created_at) }}</el-descriptions-item>
          <el-descriptions-item label="船到订单号" v-if="currentOrder.neighbor_order_no">{{ currentOrder.order_no }}</el-descriptions-item>
          <el-descriptions-item label="配送平台">{{ getPlatformText(currentOrder.platform_type) }}</el-descriptions-item>
          <el-descriptions-item label="订单金额">¥{{ formatAmount(currentOrder.local_info && currentOrder.local_info.total_amount) }}</el-descriptions-item>
        </el-descriptions>

        <!-- 配送信息 -->
        <el-descriptions title="收货信息" :column="2" border style="margin-top: 20px;">
          <el-descriptions-item label="收货人姓名">{{ currentOrder.receiver_info && currentOrder.receiver_info.name }}</el-descriptions-item>
          <el-descriptions-item label="收货人电话">{{ currentOrder.receiver_info && currentOrder.receiver_info.phone }}</el-descriptions-item>
          <el-descriptions-item label="收货地址" :span="2">{{ currentOrder.receiver_info && currentOrder.receiver_info.address }}</el-descriptions-item>
          <el-descriptions-item label="商品信息" :span="2">
            <div v-if="currentOrder.goods_info">
              <div style="display: flex; flex-wrap: wrap; gap: 20px;">
                <span><strong>订单类型:</strong> {{ currentOrder.goods_info.type_text || '未知类型' }}</span>
                <span><strong>预估价格:</strong> ¥{{ formatAmount(currentOrder.goods_info.estimate_goods_price) }}</span>
                <span><strong>商品重量:</strong> {{ currentOrder.goods_info.weight }}kg</span>
              </div>
            </div>
            <span v-else>-</span>
          </el-descriptions-item>
        </el-descriptions>

        <!-- 骑手信息 -->
        <div style="margin-top: 20px;" v-if="currentOrder.shipper_info">
          <h4>骑手信息</h4>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="骑手姓名">{{ currentOrder.shipper_info.name || '-' }}</el-descriptions-item>
            <el-descriptions-item label="骑手电话">{{ currentOrder.shipper_info.mobile || '-' }}</el-descriptions-item>
            <el-descriptions-item label="当前状态" :span="2">
              <el-tag :type="getOrderStatusColor(currentOrder.shipper_info.current_status)" size="small">
                {{ currentOrder.shipper_info.status_description || '状态未知' }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
          
          <!-- 配送时间线 - 基于状态感知显示 -->
          <div v-if="currentOrder.shipper_info.visible_timeline && Object.keys(currentOrder.shipper_info.visible_timeline).length > 0" style="margin-top: 15px;">
            <h5 style="margin-bottom: 10px;">配送进度</h5>
            <el-timeline size="small">
              <el-timeline-item
                v-for="(timeInfo, timeKey) in currentOrder.shipper_info.visible_timeline"
                :key="timeKey"
                :timestamp="timeInfo.time_text || '-'"
                :type="getTimelineType(timeKey, currentOrder.shipper_info.current_status)">
                {{ timeInfo.label }}
              </el-timeline-item>
            </el-timeline>
          </div>
          
          <!-- 取消原因（如果有） -->
          <div v-if="currentOrder.shipper_info.cancel_reason" style="margin-top: 10px;">
            <el-alert
              :title="'取消原因: ' + currentOrder.shipper_info.cancel_reason"
              type="warning"
              :closable="false"
              show-icon>
            </el-alert>
          </div>
        </div>

        <!-- 当没有骑手信息时显示提示 -->
        <div v-else style="margin-top: 20px;">
          <h4>骑手信息</h4>
          <el-alert
            title="暂无骑手信息"
            description="订单尚未分配骑手或骑手信息暂未同步"
            type="info"
            :closable="false"
            show-icon>
          </el-alert>
        </div>

        <!-- 费用明细 -->
        <el-descriptions title="费用明细" :column="3" border style="margin-top: 20px;">
          <el-descriptions-item label="总金额">¥{{ formatAmount((currentOrder.fee_info && currentOrder.fee_info.total_amount) || (currentOrder.local_info && currentOrder.local_info.total_amount) || 0) }}</el-descriptions-item>
          <el-descriptions-item label="配送费">¥{{ formatAmount((currentOrder.fee_info && currentOrder.fee_info.delivery_fee) || (currentOrder.local_info && currentOrder.local_info.delivery_fee) || 0) }}</el-descriptions-item>
          <el-descriptions-item label="小费">¥{{ formatAmount((currentOrder.fee_info && currentOrder.fee_info.tip_amount) || (currentOrder.local_info && currentOrder.local_info.tip_amount) || 0) }}</el-descriptions-item>
        </el-descriptions>

        <!-- 订单备注 -->
        <div style="margin-top: 20px;" v-if="currentOrder.note">
          <h4>订单备注</h4>
          <p>{{ currentOrder.note }}</p>
        </div>

        <!-- 配送状态 -->
        <div style="margin-top: 20px;" v-if="currentOrder.delivery_status">
          <h4>配送状态</h4>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="订单状态">
              <el-tag :type="getDeliveryStatusColor(currentOrder.delivery_status.order_state)" size="small">
                {{ currentOrder.delivery_status.order_state_text || '未知状态' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="子状态">
              <el-tag :type="getSubStateColor(currentOrder.delivery_status.order_sub_state)" size="small">
                {{ currentOrder.delivery_status.order_sub_state_text || '无' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="发单时间">{{ formatTimestamp(currentOrder.delivery_status.publish_time) }}</el-descriptions-item>
            <el-descriptions-item label="配送距离">
              <span v-if="currentOrder.delivery_status.distance > 0">
                <i class="el-icon-map-location"></i>
                {{ formatDistance(currentOrder.delivery_status.distance) }}
              </span>
              <span v-else>-</span>
            </el-descriptions-item>
          </el-descriptions>
          
          <!-- 骑手位置信息（如果可用） -->
          <div v-if="currentOrder.delivery_status.rider_location && currentOrder.delivery_status.rider_location.latitude" style="margin-top: 15px;">
            <h5 style="margin-bottom: 10px;">骑手位置</h5>
            <el-descriptions :column="3" border size="small">
              <el-descriptions-item label="纬度">{{ currentOrder.delivery_status.rider_location.latitude }}</el-descriptions-item>
              <el-descriptions-item label="经度">{{ currentOrder.delivery_status.rider_location.longitude }}</el-descriptions-item>
              <el-descriptions-item label="更新时间">{{ currentOrder.delivery_status.rider_location.last_update || '-' }}</el-descriptions-item>
            </el-descriptions>
          </div>
        </div>

        <!-- 其他订单信息 -->
        <div style="margin-top: 20px;" v-if="currentOrder.consumer_isv || currentOrder.consumer_order_no">
          <h4>第三方信息</h4>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="第三方平台" v-if="currentOrder.consumer_isv">
              {{ currentOrder.consumer_isv_text || currentOrder.consumer_isv }}
            </el-descriptions-item>
            <el-descriptions-item label="第三方订单号" v-if="currentOrder.consumer_order_no">
              {{ currentOrder.consumer_order_no }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
      <div slot="footer">
        <el-button @click="detailVisible = false">关闭</el-button>
        <el-button
          type="primary"
          @click="refreshOrderStatus(currentOrder)"
          :loading="refreshSingleLoading">
          <i class="el-icon-refresh"></i>
          刷新状态
        </el-button>
      </div>
    </el-dialog>

    <!-- 骑手位置弹窗 -->
    <el-dialog
      title="骑手实时位置"
      :visible.sync="riderLocationVisible"
      width="800px"
      :close-on-click-modal="false"
      :top="'5vh'"
      custom-class="rider-location-dialog"
      :modal-append-to-body="false">
      <div v-if="currentRiderLocation">
        <!-- 骑手信息 -->
        <div class="rider-header">
          <div class="rider-info-detail">
            <el-avatar :size="60" :src="currentRiderLocation.avatar || ''">
              {{ currentRiderLocation.rider_info.name.charAt(0) }}
            </el-avatar>
            <div class="rider-details">
              <div class="rider-name">{{ currentRiderLocation.rider_info.name }}</div>
              <div class="rider-mobile">{{ currentRiderLocation.rider_info.mobile }}</div>
              <div class="rider-status">
                <el-tag type="success" size="small">
                  配送中
                </el-tag>
              </div>
            </div>
          </div>
          <div class="location-info">
            <div class="location-item">
              <i class="el-icon-s-custom"></i>
              <span>骑手实时位置</span>
            </div>
            <div class="location-time">
              更新时间: {{ formatTime(lastUpdateTime) }}
            </div>
          </div>
        </div>

        <!-- 地图显示区域 -->
        <div class="rider-map-container">
          <TencentMap
            ref="riderMap"
            v-if="mapMarkers.length > 0"
            :width="mapConfig.width"
            :height="mapConfig.height"
            :center="mapCenter"
            :zoom="mapConfig.zoom"
            :markers="mapMarkers"
            :show-controls="true"
            markerIconType="rider"
            @map-ready="handleMapReady"
            @marker-click="handleMarkerClick"
          />
          
          <!-- 无位置数据时的提示 -->
          <div v-else class="rider-map-placeholder">
            <i class="el-icon-user-solid"></i>
            <p>暂无位置信息</p>
            <p class="map-note">骑手暂未开启位置共享或订单尚未开始配送</p>
          </div>
          
          <!-- 位置信息面板 -->
          <div v-if="mapMarkers.length > 0" class="location-panel">
            <div class="location-stats">
              <div class="stat-item" v-if="getRiderMarker() && getDestinationMarker()">
                <span class="label">预计距离:</span>
                <span class="value">{{ getDistanceText() }}</span>
              </div>
              <div class="stat-item">
                <span class="label">最后更新:</span>
                <span class="value">{{ formatDate(currentRiderLocation.location_updated_at) }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 配送进度 -->
        <div class="delivery-progress">
          <div class="progress-header">
            <h4>配送进度</h4>
            <!-- 刷新控制区域 -->
            <div class="refresh-controls-inline">
              <el-switch
                v-model="autoRefreshEnabled"
                @change="handleAutoRefreshToggle"
                active-text="自动刷新"
                inactive-text="手动刷新"
                size="small">
              </el-switch>
              <span v-if="autoRefreshEnabled" class="refresh-interval">每{{ autoRefreshInterval }}秒更新</span>
              <span v-if="lastUpdateTime" class="last-update">上次更新: {{ formatTime(lastUpdateTime) }}</span>
              <el-button
                size="mini"
                type="primary"
                @click="refreshRiderLocation"
                :loading="refreshRiderLoading">
                <i class="el-icon-refresh"></i>
                立即刷新
              </el-button>
            </div>
          </div>
          
          <!-- 横向时间轴 -->
          <div class="horizontal-timeline">
            <div 
              v-for="(item, index) in deliveryTimeline" 
              :key="`timeline-${index}`"
              class="timeline-item"
              :class="item.type">
              <div class="timeline-dot"></div>
              <div class="timeline-content">
                <div class="timeline-title">{{ item.content }}</div>
                <div class="timeline-time">{{ item.timestamp }}</div>
              </div>
              <div v-if="index < deliveryTimeline.length - 1" class="timeline-line"></div>
            </div>
          </div>
        </div>
      </div>
      <div slot="footer">
        <div class="dialog-buttons">
          <el-button @click="closeRiderLocationDialog">关闭</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 取消订单弹窗 -->
    <el-dialog
      title="取消订单"
      :visible.sync="cancelVisible"
      width="500px"
      :close-on-click-modal="false">
      <div v-if="currentOrder">
        <el-alert
          title="取消订单说明"
          type="warning"
          :closable="false"
          style="margin-bottom: 15px;">
          取消订单后将自动退款到商户账户，请确认操作。
        </el-alert>

        <el-form :model="cancelForm" label-width="100px">
          <el-form-item label="订单编号:">
            <span>{{ currentOrder.neighbor_order_no || currentOrder.order_no }}</span>
          </el-form-item>
          <el-form-item label="退款金额:">
            <span style="color: #E6A23C; font-weight: 500;">¥{{ formatAmount(currentOrder.total_amount) }}</span>
          </el-form-item>
          <el-form-item label="取消原因:" required>
            <el-select v-model="cancelForm.cancel_reason" placeholder="请选择取消原因" class="ele-fluid">
              <el-option label="商户主动取消" value="merchant_cancel"></el-option>
              <el-option label="无法联系收件人" value="contact_failed"></el-option>
              <el-option label="地址信息错误" value="address_error"></el-option>
              <el-option label="商品问题" value="product_issue"></el-option>
              <el-option label="其他原因" value="other"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="取消备注:">
            <el-input
              type="textarea"
              v-model="cancelForm.cancel_remark"
              placeholder="请输入取消备注（可选）"
              :rows="3">
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer">
        <el-button @click="cancelVisible = false">取消</el-button>
        <el-button
          type="danger"
          @click="confirmCancelOrder"
          :loading="cancelLoading">
          确认取消订单
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getOrderStats,
  getOrderDetail,
  getRiderLocation,
  refreshOrderStatus as refreshOrderStatusAPI,
  cancelOrder as cancelOrderAPI,
  batchRefreshStatus,
  exportOrderData
} from '@/api/chuandao';
import TencentMap from '@/components/TencentMap.vue';
import { 
  convertRiderDataToMapMarkers,
  calculateDistance,
  formatDistance,
  createMapConfig
} from '@/utils/riderMapAdapter';

export default {
  name: 'ChuandaoOrderIndex',
  components: {
    TencentMap
  },
  data() {
    return {
      // 表格配置
      url: 'chuandao/order/list',
      where: {
        order_no: '',
        order_status: null
      },
      dateRange: null,

      columns: [
        {
          columnKey: 'selection',
          type: 'selection',
          width: 45,
          align: 'center'
        },
        {
          prop: 'order_info',
          label: '订单信息',
          slot: 'order_info',
          minWidth: 180
        },
        {
          prop: 'delivery_info',
          label: '配送信息',
          slot: 'delivery_info',
          minWidth: 250
        },
        {
          prop: 'order_status',
          label: '订单状态',
          slot: 'order_status',
          width: 120,
          align: 'center'
        },
        {
          prop: 'rider_info',
          label: '骑手信息',
          slot: 'rider_info',
          width: 120
        },
        {
          prop: 'order_amount',
          label: '订单金额',
          slot: 'order_amount',
          width: 120,
          align: 'right'
        },
        {
          columnKey: 'action',
          label: '操作',
          width: 180,
          slot: 'action',
          align: 'center'
        }
      ],
      selection: [],

      // 弹窗状态
      detailVisible: false,
      riderLocationVisible: false,
      cancelVisible: false,

      // 当前数据
      currentOrder: null,
      currentRiderLocation: null,
      currentOrderId: null,  // 保存当前订单ID用于刷新

      // 地图相关数据
      mapMarkers: [],
      mapCenter: null,
      mapInstance: null, // 地图实例引用
      mapConfig: createMapConfig({
        width: '100%',
        height: '400px',
        zoom: 12
      }),

      // 实时更新相关
      autoRefreshEnabled: true,
      autoRefreshInterval: 30, // 秒
      autoRefreshTimer: null,
      lastUpdateTime: null,

      // 统计数据
      stats: null,

      // 取消订单表单
      cancelForm: {
        cancel_reason: '',
        cancel_remark: ''
      },

      // 配送时间轴
      deliveryTimeline: [],

      // 加载状态
      refreshLoading: false,
      refreshSingleLoading: false,
      refreshRiderLoading: false,
      cancelLoading: false
    };
  },

  computed: {
    // 表格查询参数
    tableWhere() {
      const params = { ...this.where };

      // 添加日期范围
      if (this.dateRange && this.dateRange.length === 2) {
        params.start_time = this.dateRange[0];
        params.end_time = this.dateRange[1];
      }

      return params;
    }
  },

  created() {
    this.loadStats();
  },

  methods: {
    // 重新加载表格
    reload() {
      this.$refs.table.reload();
      this.loadStats();
    },

    // 重置搜索
    reset() {
      this.where = {
        order_no: '',
        order_status: null
      };
      this.dateRange = null;
      this.reload();
    },

    // 加载统计数据
    loadStats() {
      const params = { ...this.tableWhere };

      getOrderStats(params).then(res => {
        if (res.code === 0) {
          this.stats = res.data;
        }
      }).catch(error => {
        console.error('获取统计数据失败:', error);
        // 使用模拟数据作为降级
        this.stats = {
          total_orders: 1856,
          pending_orders: 25,
          processing_orders: 87,
          completed_orders: 1532,
          cancelled_orders: 212,
          total_amount: 285600.00
        };
      });
    },

    // 显示订单详情
    showOrderDetail(row) {
      getOrderDetail(row.id).then(res => {
        if (res.code === 0) {
          this.currentOrder = res.data;
          this.detailVisible = true;
        } else {
          this.$message.error(res.message || '获取订单详情失败');
        }
      }).catch(error => {
        console.error('获取订单详情失败:', error);
        this.$message.error('获取订单详情失败，请重试');
      });
    },

    // 显示骑手位置
    showRiderLocation(row) {
      // 保存订单ID用于后续刷新
      this.currentOrderId = row.id;
      
      getRiderLocation(row.id).then(res => {
        if (res.code === 0) {
          this.currentRiderLocation = res.data;
          this.buildDeliveryTimeline(res.data);
          
          // 转换数据为地图格式
          this.updateMapData(res, row);
          
          // 设置初始更新时间
          this.lastUpdateTime = new Date();
          
          // 显示弹窗
          this.riderLocationVisible = true;
          
          // 如果启用自动刷新，开始定时刷新
          if (this.autoRefreshEnabled) {
            this.$nextTick(() => {
              this.startAutoRefresh();
            });
          }
        } else {
          this.$message.error(res.message || '获取骑手位置失败');
        }
      }).catch(error => {
        console.error('获取骑手位置失败:', error);
        this.$message.error('获取骑手位置失败，请重试');
      });
    },

    // 构建配送时间轴
    buildDeliveryTimeline(data) {
      this.deliveryTimeline = [
        {
          timestamp: data.accepted_at ? this.formatDate(data.accepted_at) : '待接单',
          content: '骑手已接单',
          type: 'success'
        },
        {
          timestamp: data.pickup_at ? this.formatDate(data.pickup_at) : '待取货',
          content: data.pickup_at ? '已取货' : '前往取货点',
          type: data.pickup_at ? 'success' : 'primary'
        },
        {
          timestamp: data.delivery_at ? this.formatDate(data.delivery_at) : '配送中',
          content: data.delivery_at ? '已送达' : '配送中',
          type: data.delivery_at ? 'success' : 'warning'
        }
      ];
    },

    // 刷新订单状态
    refreshOrderStatus(row) {
      this.refreshSingleLoading = true;
      refreshOrderStatusAPI(row.id).then(res => {
        if (res.code === 0) {
          this.$message.success('订单状态已更新');
          this.reload();
          if (this.detailVisible) {
            this.currentOrder = { ...this.currentOrder, ...res.data };
          }
        } else {
          this.$message.error(res.message || '刷新状态失败');
        }
      }).catch(error => {
        console.error('刷新订单状态失败:', error);
        this.$message.error('刷新状态失败，请重试');
      }).finally(() => {
        this.refreshSingleLoading = false;
      });
    },

    // 刷新实时状态
    refreshRealtime() {
      this.refreshLoading = true;
      // 刷新当前页面所有订单的状态
      const orderIds = this.$refs.table.data.map(item => item.id);

      batchRefreshStatus(orderIds).then(res => {
        if (res.code === 0) {
          this.$message.success(`已刷新 ${res.data.updated_count} 个订单状态`);
          this.reload();
        } else {
          this.$message.error(res.message || '批量刷新失败');
        }
      }).catch(error => {
        console.error('批量刷新状态失败:', error);
        this.$message.error('批量刷新失败，请重试');
      }).finally(() => {
        this.refreshLoading = false;
      });
    },

    // 刷新骑手位置
    refreshRiderLocation() {
      if (!this.currentOrderId) return;

      this.refreshRiderLoading = true;
      getRiderLocation(this.currentOrderId).then(res => {
        if (res.code === 0) {
          this.currentRiderLocation = res.data;
          this.buildDeliveryTimeline(res.data);
          
          // 更新地图数据
          this.updateMapData(res);
          
          // 更新最后更新时间
          this.lastUpdateTime = new Date();
          
          this.$message.success('骑手位置已更新');
        } else {
          this.$message.error(res.message || '刷新位置失败');
        }
      }).catch(error => {
        console.error('刷新骑手位置失败:', error);
        this.$message.error('刷新位置失败，请重试');
      }).finally(() => {
        this.refreshRiderLoading = false;
      });
    },

    // 取消订单
    cancelOrder(row) {
      this.currentOrder = row;
      this.cancelForm = {
        cancel_reason: '',
        cancel_remark: ''
      };
      this.cancelVisible = true;
    },

    // 确认取消订单
    confirmCancelOrder() {
      if (!this.cancelForm.cancel_reason) {
        this.$message.warning('请选择取消原因');
        return;
      }

      this.cancelLoading = true;
      const params = {
        order_id: this.currentOrder.id,
        cancel_reason: this.cancelForm.cancel_reason,
        cancel_remark: this.cancelForm.cancel_remark
      };

      cancelOrderAPI(params).then(res => {
        if (res.code === 0) {
          this.$message.success('订单取消成功，退款将原路返回');
          this.cancelVisible = false;
          this.reload();
        } else {
          this.$message.error(res.message || '取消订单失败');
        }
      }).catch(error => {
        console.error('取消订单失败:', error);
        this.$message.error('取消订单失败，请重试');
      }).finally(() => {
        this.cancelLoading = false;
      });
    },

    // 判断是否可以取消订单
    canCancelOrder(row) {
      // 待接单、已接单状态可以取消
      return [1, 2].includes(row.order_status);
    },

    // 判断是否可以申请退款
    canRefundOrder(row) {
      // 已完成的订单可以申请退款
      return row.order_status === 5;
    },

    // 处理订单操作
    handleOrderAction(command) {
      const { action, row } = command;

      switch (action) {
        case 'track':
          this.trackOrder(row);
          break;
        case 'refund':
          this.applyRefund(row);
          break;
        case 'complaint':
          this.submitComplaint(row);
          break;
      }
    },

    // 订单追踪
    trackOrder(row) {
      this.$message.info(`订单 ${row.order_no} 追踪功能开发中...`);
    },

    // 申请退款
    applyRefund(row) {
      this.$message.info(`订单 ${row.order_no} 退款功能开发中...`);
    },

    // 投诉建议
    submitComplaint(row) {
      this.$message.info(`订单 ${row.order_no} 投诉功能开发中...`);
    },

    // 批量刷新状态
    batchRefreshStatus() {
      if (this.selection.length === 0) {
        this.$message.warning('请先选择要操作的订单');
        return;
      }
      
      const orderIds = this.selection.map(item => item.id);

      batchRefreshStatus(orderIds).then(res => {
        if (res.code === 0) {
          this.$message.success(`已刷新 ${res.data.updated_count} 个订单状态`);
          this.reload();
        } else {
          this.$message.error(res.message || '批量刷新失败');
        }
      }).catch(error => {
        console.error('批量刷新失败:', error);
        this.$message.error('批量刷新失败，请重试');
      });
    },

    // 智能导出订单数据
    async exportData() {
      try {
        // 显示加载提示
        const loading = this.$loading({
          lock: true,
          text: '正在导出数据，请稍候...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });

        // 构建导出参数 - 根据是否有选中记录决定导出模式
        let params;
        if (this.selection && this.selection.length > 0) {
          // 选中导出模式：传递选中的ID数组，忽略搜索条件
          params = {
            mode: 'selected',
            ids: this.selection.map(item => item.id)
          };
          console.log('选中导出模式，导出记录ID:', params.ids);
        } else {
          // 条件导出模式：传递搜索条件
          params = {
            mode: 'filter',
            ...this.tableWhere
          };
          console.log('条件导出模式，搜索条件:', this.tableWhere);
        }

        // 调用导出API
        const response = await exportOrderData(params);
        
        loading.close();

        // 创建下载链接
        const blob = new Blob([response], { type: 'text/csv;charset=utf-8' });
        const url = window.URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.style.display = 'none';
        link.href = url;
        
        // 生成文件名 - 根据导出模式添加标识
        const now = new Date();
        const timestamp = now.getFullYear() + 
          String(now.getMonth() + 1).padStart(2, '0') + 
          String(now.getDate()).padStart(2, '0') + '_' +
          String(now.getHours()).padStart(2, '0') + 
          String(now.getMinutes()).padStart(2, '0') + 
          String(now.getSeconds()).padStart(2, '0');
        
        const modeText = params.mode === 'selected' ? '选中记录' : '筛选结果';
        link.download = `船到订单数据_${modeText}_${timestamp}.csv`;
        
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);

        // 显示成功提示
        const exportCount = params.mode === 'selected' ? this.selection.length : '符合条件的';
        this.$message.success(`数据导出成功！已导出${exportCount}条记录`);

      } catch (error) {
        console.error('导出失败:', error);
        this.$message.error('导出失败：' + (error.message || '网络错误'));
      }
    },


    // 获取订单状态文本
    getOrderStatusText(status) {
      const statusMap = {
        1: '待接单',
        2: '已接单',
        3: '取货中',
        4: '配送中',
        5: '已完成',
        6: '已取消',
        7: '异常'
      };
      return statusMap[status] || '未知';
    },

    // 获取订单状态颜色
    getOrderStatusColor(status) {
      const colorMap = {
        1: 'info',
        2: 'primary',
        3: 'warning',
        4: 'warning',
        5: 'success',
        6: 'danger',
        7: 'danger'
      };
      return colorMap[status] || '';
    },

    // 获取配送状态颜色
    getDeliveryStatusColor(state) {
      const colorMap = {
        0: 'info',      // 待发单
        1: 'primary',   // 待接单
        2: 'warning',   // 配送中
        3: 'success',   // 已完成
        4: 'danger',    // 已取消
        5: 'danger'     // 异常
      };
      return colorMap[state] || 'info';
    },

    // 获取骑手状态文本
    getRiderStatusText(status) {
      const statusMap = {
        1: '在线',
        2: '忙碌',
        3: '离线'
      };
      return statusMap[status] || '未知';
    },

    // 获取骑手状态颜色
    getRiderStatusColor(status) {
      const colorMap = {
        1: 'success',
        2: 'warning',
        3: 'info'
      };
      return colorMap[status] || '';
    },

    // 格式化金额
    formatAmount(amount) {
      if (amount === null || amount === undefined) return '0.00';
      return parseFloat(amount).toLocaleString('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      });
    },

    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '-';
      const date = new Date(dateString);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      });
    },

    // 格式化时间戳
    formatTimestamp(timestamp) {
      if (!timestamp || timestamp === 0) return '-';
      const date = new Date(timestamp * 1000);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      });
    },

    // 获取平台文本
    getPlatformText(platformType) {
      const platformMap = {
        'DD': '达达',
        'FN': '蜂鸟',
        'SS': '闪送',
        'UU': 'UU跑腿',
        'SF': '顺丰',
        'GXD': '裹小递',
        'XZWM': '小镇外卖',
        'MTQK': '美团快速达',
        'KFW': '快服务',
        'SFYX': '顺丰优享'
      };
      return platformMap[platformType] || platformType || '未知平台';
    },

    // 获取时间线类型
    getTimelineType(timeKey, currentStatus) {
      // 根据时间节点和当前状态返回时间线的颜色类型
      const typeMap = {
        'accept_time': 'primary',   // 接单时间 - 蓝色
        'arrive_time': 'warning',   // 到店时间 - 橙色
        'confirm_time': 'warning',  // 确认取货时间 - 橙色
        'complete_time': 'success', // 完成时间 - 绿色
        'cancel_time': 'danger'     // 取消时间 - 红色
      };
      
      // 如果订单已取消，所有时间线都用danger类型
      if (currentStatus === -1) { // 已取消状态（官方API状态码）
        return 'danger';
      }
      
      return typeMap[timeKey] || 'info';
    },

    // 获取子状态颜色
    getSubStateColor(subState) {
      // 完全按照船到官方文档的子状态编码
      const colorMap = {
        '0': 'danger',    // 主动取消（状态-1时）
        '1': 'danger',    // 配送平台取消（状态-1时）
        '41': 'success',  // 配送中（状态4时）
        '42': 'warning'   // 送回中（状态4时）
      };
      return colorMap[String(subState)] || 'info';
    },

    // 格式化距离显示
    formatDistance(distance) {
      if (distance === 0 || distance === null || distance === undefined) {
        return '未知';
      }
      
      if (distance < 1000) {
        return distance + '米';
      } else {
        return (distance / 1000).toFixed(1) + '公里';
      }
    },

    // ===== 地图相关方法 =====

    // 更新地图数据
    updateMapData(riderApiResponse, orderData = null) {
      try {
        // 使用数据适配器转换数据
        const mapData = convertRiderDataToMapMarkers(riderApiResponse, orderData);

        this.mapMarkers = mapData.markers;
        this.mapCenter = mapData.center;

        console.log('地图数据已更新:', mapData);

        // 如果地图已经加载且有标记点，自动调整视野
        if (this.mapInstance && this.mapMarkers.length > 0) {
          this.$nextTick(() => {
            setTimeout(() => {
              if (this.$refs.riderMap && typeof this.$refs.riderMap.fitBounds === 'function') {
                this.$refs.riderMap.fitBounds();
              }
            }, 300);
          });
        }
      } catch (error) {
        console.error('更新地图数据失败:', error);
        this.mapMarkers = [];
        this.mapCenter = null;
      }
    },

    // 地图准备就绪事件
    handleMapReady(mapInstance) {
      console.log('地图加载完成:', mapInstance);
      this.mapInstance = mapInstance;

      // 如果有标记点，自动调整地图视野
      if (this.mapMarkers.length > 0) {
        this.$nextTick(() => {
          // 延迟执行自适应，确保地图完全渲染
          setTimeout(() => {
            // 通过 $refs 调用 TencentMap 组件的 fitBounds 方法
            if (this.$refs.riderMap && typeof this.$refs.riderMap.fitBounds === 'function') {
              this.$refs.riderMap.fitBounds();
            }
          }, 800);
        });
      }
    },

    // 地图标记点击事件
    handleMarkerClick(markerProperties) {
      console.log('标记点被点击:', markerProperties);
      
      // 可以在这里添加点击标记的逻辑，比如显示详细信息
      if (markerProperties.type === 'rider') {
        this.$message.info('当前骑手位置');
      } else if (markerProperties.type === 'destination') {
        this.$message.info('配送目的地');
      }
    },

    // 获取骑手标记点
    getRiderMarker() {
      return this.mapMarkers.find(marker => marker.type === 'rider');
    },

    // 获取目的地标记点
    getDestinationMarker() {
      return this.mapMarkers.find(marker => marker.type === 'destination');
    },

    // 获取距离文本
    getDistanceText() {
      const riderMarker = this.getRiderMarker();
      const destMarker = this.getDestinationMarker();
      
      if (!riderMarker || !destMarker) {
        return '计算中...';
      }
      
      const distance = calculateDistance(
        { lat: riderMarker.lat, lng: riderMarker.lng },
        { lat: destMarker.lat, lng: destMarker.lng }
      );
      
      return formatDistance(distance);
    },

    // ===== 实时更新相关方法 =====

    // 处理自动刷新开关
    handleAutoRefreshToggle(enabled) {
      if (enabled) {
        this.startAutoRefresh();
      } else {
        this.stopAutoRefresh();
      }
    },

    // 开始自动刷新
    startAutoRefresh() {
      // 清除现有定时器
      this.stopAutoRefresh();
      
      // 设置新的定时器
      this.autoRefreshTimer = setInterval(() => {
        if (this.riderLocationVisible && this.currentRiderLocation) {
          this.refreshRiderLocationSilently();
        }
      }, this.autoRefreshInterval * 1000);
      
      console.log(`自动刷新已启动，间隔 ${this.autoRefreshInterval} 秒`);
    },

    // 停止自动刷新
    stopAutoRefresh() {
      if (this.autoRefreshTimer) {
        clearInterval(this.autoRefreshTimer);
        this.autoRefreshTimer = null;
        console.log('自动刷新已停止');
      }
    },

    // 静默刷新骑手位置（不显示loading和消息）
    refreshRiderLocationSilently() {
      if (!this.currentOrderId) return;

      getRiderLocation(this.currentOrderId).then(res => {
        if (res.code === 0) {
          this.currentRiderLocation = res.data;
          this.buildDeliveryTimeline(res.data);
          
          // 更新地图数据
          this.updateMapData(res);
          
          // 更新最后更新时间
          this.lastUpdateTime = new Date();
          
          console.log('骑手位置已自动更新');
        }
      }).catch(error => {
        console.error('自动刷新骑手位置失败:', error);
        // 静默失败，不显示错误消息
      });
    },

    // 关闭骑手位置弹窗
    closeRiderLocationDialog() {
      // 停止自动刷新
      this.stopAutoRefresh();
      
      // 重置数据
      this.riderLocationVisible = false;
      this.currentRiderLocation = null;
      this.currentOrderId = null;
      this.mapMarkers = [];
      this.mapCenter = null;
      this.lastUpdateTime = null;
    },

    // 格式化时间显示
    formatTime(date) {
      if (!date) return '';
      
      const now = new Date();
      const diffMs = now - date;
      const diffSeconds = Math.floor(diffMs / 1000);
      
      if (diffSeconds < 60) {
        return `${diffSeconds}秒前`;
      } else if (diffSeconds < 3600) {
        const minutes = Math.floor(diffSeconds / 60);
        return `${minutes}分钟前`;
      } else {
        return date.toLocaleTimeString('zh-CN', {
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit'
        });
      }
    }
  },

  // Vue生命周期 - 组件销毁时清理定时器
  beforeDestroy() {
    this.stopAutoRefresh();
  }
};
</script>

<style scoped>
.ele-form-search {
  margin-bottom: 20px;
}

/* 统计卡片样式 */
.order-stats {
  margin-bottom: 20px;
}

.stat-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  display: flex;
  align-items: center;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: all 0.3s;
  position: relative;
  overflow: hidden;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.15);
}

.stat-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 4px;
  height: 100%;
}

.stat-card.total::before {
  background: linear-gradient(45deg, #409EFF, #66B1FF);
}

.stat-card.pending::before {
  background: linear-gradient(45deg, #909399, #A6A9AD);
}

.stat-card.processing::before {
  background: linear-gradient(45deg, #E6A23C, #EEBE77);
}

.stat-card.completed::before {
  background: linear-gradient(45deg, #67C23A, #85CE61);
}

.stat-card.cancelled::before {
  background: linear-gradient(45deg, #F56C6C, #F78989);
}

.stat-card.amount::before {
  background: linear-gradient(45deg, #722ED1, #9254DE);
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 20px;
  color: white;
}

.stat-card.total .stat-icon {
  background: linear-gradient(45deg, #409EFF, #66B1FF);
}

.stat-card.pending .stat-icon {
  background: linear-gradient(45deg, #909399, #A6A9AD);
}

.stat-card.processing .stat-icon {
  background: linear-gradient(45deg, #E6A23C, #EEBE77);
}

.stat-card.completed .stat-icon {
  background: linear-gradient(45deg, #67C23A, #85CE61);
}

.stat-card.cancelled .stat-icon {
  background: linear-gradient(45deg, #F56C6C, #F78989);
}

.stat-card.amount .stat-icon {
  background: linear-gradient(45deg, #722ED1, #9254DE);
}

.stat-content {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

/* 表格内容样式 */
.order-info {
  display: flex;
  flex-direction: column;
}

.order-main {
  margin-bottom: 5px;
}

.order-no {
  font-weight: 500;
  margin-bottom: 3px;
}

.order-time {
  font-size: 12px;
  color: #909399;
}

.order-id {
  font-size: 12px;
  color: #C0C4CC;
}


.delivery-info {
  display: flex;
  flex-direction: column;
}

.delivery-item {
  margin-bottom: 3px;
}

.delivery-item .label {
  color: #909399;
  font-size: 12px;
  display: inline-block;
  width: 35px;
}

.delivery-item .address {
  font-size: 13px;
}

.status-info {
  text-align: center;
}

.status-time {
  font-size: 11px;
  color: #C0C4CC;
  margin-top: 5px;
}

.rider-info {
  display: flex;
  flex-direction: column;
}

.rider-main {
  display: flex;
  align-items: center;
  margin-bottom: 2px;
}

.rider-name {
  font-weight: 500;
  margin-right: 5px;
}

.rider-mobile {
  font-size: 12px;
  color: #909399;
}

.no-rider {
  color: #C0C4CC;
  font-size: 12px;
  text-align: center;
}

.amount-info {
  text-align: right;
}

.total-amount {
  color: #E6A23C;
  font-weight: 500;
  font-size: 16px;
  margin-bottom: 3px;
}

.fee-detail {
  font-size: 12px;
  color: #909399;
}

/* 骑手位置弹窗样式 */
.rider-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px;
  margin-bottom: 20px;
  color: white;
}

.rider-info-detail {
  display: flex;
  align-items: center;
}

.rider-details {
  margin-left: 15px;
}

.rider-details .rider-name {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 5px;
}

.rider-details .rider-mobile {
  font-size: 14px;
  opacity: 0.9;
  margin-bottom: 5px;
}

.location-info {
  text-align: right;
}

.location-item {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}

.location-item i {
  margin-right: 5px;
}

.location-time {
  font-size: 12px;
  opacity: 0.8;
}

.rider-map-container {
  margin-bottom: 20px;
  border: 1px solid #DCDFE6;
  border-radius: 4px;
  overflow: hidden;
}

.rider-map-placeholder {
  height: 250px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #F5F7FA;
  color: #909399;
}

.rider-map-placeholder i {
  font-size: 40px;
  margin-bottom: 15px;
}

.rider-map-placeholder p {
  margin: 0;
  font-size: 14px;
}

.map-note {
  font-size: 12px !important;
  margin-top: 8px !important;
}

.coordinates {
  margin-top: 10px;
  font-size: 12px;
}

.delivery-progress {
  margin-top: 20px;
}

.delivery-progress h4 {
  margin-bottom: 15px;
  color: #303133;
}

/* 骑手位置图标样式 */
.el-icon-location-information {
  color: #409EFF;
  cursor: pointer;
  transition: color 0.3s;
}

.el-icon-location-information:hover {
  color: #66B1FF;
}

.el-icon-s-custom {
  color: #409EFF;
  cursor: pointer;
  transition: color 0.3s;
}

.el-icon-s-custom:hover {
  color: #66B1FF;
}

.rider-map-placeholder .el-icon-user-solid {
  color: #C0C4CC;
  font-size: 48px;
}

.location-item .el-icon-s-custom {
  color: #67C23A;
  margin-right: 5px;
}

/* 操作按钮样式 */
.el-button--text {
  padding: 0;
  margin-right: 8px;
}

.el-button--text:last-child {
  margin-right: 0;
}

/* 下拉菜单样式 */
.el-dropdown {
  vertical-align: top;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .order-stats .el-col {
    margin-bottom: 15px;
  }

  .stat-card {
    padding: 15px;
  }

  .stat-icon {
    width: 40px;
    height: 40px;
    font-size: 18px;
    margin-right: 12px;
  }

  .stat-value {
    font-size: 20px;
  }

  .rider-header {
    flex-direction: column;
    text-align: center;
  }

  .rider-info-detail {
    margin-bottom: 15px;
  }

  .location-info {
    text-align: center;
  }
}

/* 表单项间距 */
.el-form-item {
  margin-bottom: 15px;
}

/* 工具栏样式 */
.ele-form-actions {
  text-align: left;
}

/* 标签样式调整 */
.el-tag {
  border-radius: 4px;
}

/* 时间轴样式调整 */
.el-timeline {
  padding-left: 0;
}

/* 弹窗标题样式 */
.el-descriptions__title {
  margin-bottom: 15px;
}

/* 地图位置信息面板样式 */
.location-panel {
  background: rgba(255, 255, 255, 0.95);
  border-top: 1px solid #EBEEF5;
  padding: 12px 16px;
}

.location-stats {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stat-item {
  display: flex;
  align-items: center;
  font-size: 13px;
}

.stat-item .label {
  color: #606266;
  margin-right: 8px;
}

.stat-item .value {
  color: #303133;
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .rider-map-container {
    margin-bottom: 15px;
  }
  
  .location-stats {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .stat-item {
    width: 100%;
    justify-content: space-between;
  }
}

/* 骑手位置对话框样式 */
.rider-location-dialog .el-dialog {
  max-height: 85vh;
  margin-top: 5vh !important;
  margin-bottom: 5vh !important;
}

.rider-location-dialog .el-dialog__body {
  max-height: calc(85vh - 120px);
  overflow-y: auto;
  padding: 15px 20px;
}

/* 确保地图组件高度合适 */
.rider-location-dialog .rider-map-container {
  height: 350px;
}

/* 配送进度头部样式 */
.progress-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 10px;
}

.progress-header h4 {
  margin: 0;
  color: #303133;
}

.refresh-controls-inline {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.refresh-controls-inline .refresh-interval {
  font-size: 12px;
  color: #67C23A;
  background: #F0F9FF;
  padding: 2px 8px;
  border-radius: 12px;
  border: 1px solid #E1F5FE;
}

.refresh-controls-inline .last-update {
  font-size: 12px;
  color: #909399;
}

/* 横向时间轴样式 */
.horizontal-timeline {
  display: flex;
  align-items: flex-start;
  overflow-x: auto;
  padding: 20px 0;
  gap: 0;
}

.timeline-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
  min-width: 120px;
  flex-shrink: 0;
}

.timeline-dot {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  border: 2px solid #DCDFE6;
  background: #FFFFFF;
  position: relative;
  z-index: 2;
  margin-bottom: 10px;
}

.timeline-item.primary .timeline-dot {
  border-color: #409EFF;
  background: #409EFF;
}

.timeline-item.success .timeline-dot {
  border-color: #67C23A;
  background: #67C23A;
}

.timeline-item.warning .timeline-dot {
  border-color: #E6A23C;
  background: #E6A23C;
}

.timeline-item.danger .timeline-dot {
  border-color: #F56C6C;
  background: #F56C6C;
}

.timeline-content {
  text-align: center;
  max-width: 100px;
}

.timeline-title {
  font-size: 12px;
  color: #303133;
  font-weight: 500;
  margin-bottom: 5px;
  line-height: 1.2;
}

.timeline-time {
  font-size: 10px;
  color: #909399;
  line-height: 1.2;
}

.timeline-line {
  position: absolute;
  top: 6px;
  left: calc(50% + 6px);
  width: calc(100% - 12px);
  height: 2px;
  background: #DCDFE6;
  z-index: 1;
}

.timeline-item.primary + .timeline-item .timeline-line,
.timeline-item.success + .timeline-item .timeline-line,
.timeline-item.warning + .timeline-item .timeline-line {
  background: #409EFF;
}

/* 移动端对话框适配 */
@media (max-width: 768px) {
  .rider-location-dialog .el-dialog {
    width: 95% !important;
    max-height: 90vh;
    margin-top: 5vh !important;
    margin-bottom: 5vh !important;
  }
  
  .rider-location-dialog .el-dialog__body {
    max-height: calc(90vh - 120px);
    padding: 10px 15px;
  }
  
  .rider-location-dialog .rider-map-container {
    height: 280px;
  }
  
  .progress-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .refresh-controls-inline {
    width: 100%;
    justify-content: flex-start;
  }
  
  .timeline-item {
    min-width: 80px;
  }
  
  .timeline-content {
    max-width: 70px;
  }
  
  .timeline-title {
    font-size: 10px;
  }
  
  .timeline-time {
    font-size: 9px;
  }
}
</style>
